package com.example.lgseckill.service;

import com.example.lgseckill.commom.Constant;
import com.example.lgseckill.commom.utils.RedisUtil;
import com.example.lgseckill.domain.SeckillOrder;
import com.example.lgseckill.domain.SeckillProduct;
import com.example.lgseckill.domain.SeckillProductPreheatVO;
import com.example.lgseckill.mapper.SeckillProductMapper;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;


/**
 * 延迟监听
 * Author:e
 * Date:2021/8/18 3:12 下午
 **/
@Component
@RocketMQMessageListener(topic = "seckillTopic", consumerGroup = "seckill-group")
public class SeckillOrderListenerService implements RocketMQListener<MessageExt> {

    private final static Logger logger = LoggerFactory.getLogger(SeckillOrderListenerService.class);

    @Autowired
    private ISeckillOrderService seckillOrderService;

    @Autowired
    private ISeckillProducttService seckillProducttService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private SeckillProductMapper seckillProductMapper;

    @Override
    public void onMessage(MessageExt messageExt) {
        Date now = new Date();
        String orderid = new String(messageExt.getBody());
        logger.info("接收到消息：{}, 重试次数：{}", orderid, messageExt.getReconsumeTimes());
        //获取订单信息
        SeckillOrder seckillOrder = seckillOrderService.getById(orderid);
        if (seckillOrder == null) return;
        //获取秒杀库存
        SeckillProduct seckillProduct = seckillProducttService.getById(seckillOrder.getSeckillId());

        //开始时间
        long startTime = seckillProduct.getStartTime().getTime();
        //结束时间
        long endTime = seckillProduct.getEndTime().getTime();
        //计算离结束还有多久时间（作为过期时间）
        long expire = (endTime - now.getTime()) / 1000;

        if (seckillOrder.getPayStatus() == 0) {
            logger.info("订单支付超时，取消：{}", orderid);
            seckillOrder.setPayStatus(2);
            seckillOrderService.updateById(seckillOrder);
            // 新增令牌，把令牌压回缓存
            redisUtil.rightPush(Constant.SECKILL_TOKEM + seckillProduct.getSeckillProductId(), seckillProduct.getSeckillProductId());
            redisUtil.expire(Constant.SECKILL_TOKEM +
                    seckillProduct.getSeckillProductId(), expire);
            return;
        }
        logger.info("订单支付成功：{}", orderid);
    }


    //public static void main(String[] args) throws MQClientException {
    //    DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("seckill-group");
    //    consumer.setNamesrvAddr("192.168.2.131:9876");
    //    consumer.subscribe("seckillTopic","*");
    //    consumer.setMessageListener(new MessageListenerConcurrently() {
    //        @Override
    //        public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
    //            for (MessageExt messageExt : list) {
    //                System.out.println(messageExt);
    //                System.out.println("收到的消息："+new String(messageExt.getBody()));
    //            }
    //            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
    //        }
    //    });
    //    consumer.start();
    //}

}
